<h1><%= @album.name %></h1>

<div class="form-group">
  <label>Select photos</label>
  <input type="file" multiple name="file">
</div>

<form action="/album" method="post">
  <input type="hidden" name="_method" value="put">
  <%= csrf_tag %>

  <ul class="list-unstyled">
    <% @album.photos.each_with_index do |photo, idx| %>
      <%= partial("photo", locals: {photo: photo, idx: idx}) %>
    <% end %>

  </ul>
  <input type="submit" value="Save" class="btn btn-primary">
</form>

<script>
  $(function() {
    $('[type=file]').fileupload({
      add: function(e, data) {
        data.progressBar = $('<div class="progress" style="width: 300px"><div class="progress-bar"></div></div>').insertAfter(".form-group");
        var options = {
          extension: data.files[0].name.match(/(\.\w+)?$/)[0], // set extension
          _: Date.now(),                                       // prevent caching
        }
        $.getJSON('/images/cache/presign', options, function(result) {
          data.formData = result['fields'];
          data.url = result['url'];
          data.paramName = 'file';
          data.submit();
        });
      },
      progress: function(e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        var percentage = progress.toString() + '%'
        data.progressBar.find(".progress-bar").css("width", percentage).html(percentage);
      },
      done: function(e, data) {
        data.progressBar.remove();

        var image = {
          id: data.formData.key.match(/cache\/(.+)/)[1], // we have to remove the prefix part
          storage: 'cache',
          metadata: {
            size:      data.files[0].size,
            filename:  data.files[0].name.match(/[^\/\\]+$/)[0], // IE returns full path
            mime_type: data.files[0].type
          }
        }

        var data = {
          photo: {image: JSON.stringify(image)},
          _csrf: $("input[name=_csrf]").val(),
        }

        $.ajax("/album/photos", {method: 'POST', data: data})
          .done(function(data) { $("ul").append(data) })
      }
    });
  });
</script>
